"""
用户管理相关的API
包括用户列表、详情、创建、更新等功能
"""
from flask import request, jsonify
from flask_jwt_extended import jwt_required, current_user
from app.extensions import db
from app.models.user import User, UserRole
from app.schemas.user import UserSchema, UserUpdateSchema
from app.utils.errors import ForbiddenError, NotFoundError
from app.api.v1 import api_v1

# 检查管理员权限装饰器
def admin_required(fn):
    """检查当前用户是否为管理员"""
    @jwt_required()
    def wrapper(*args, **kwargs):
        if not current_user.is_admin:
            raise ForbiddenError("需要管理员权限")
        return fn(*args, **kwargs)
    return wrapper

@api_v1.route('/users', methods=['GET'])
@admin_required
def get_users():
    """获取用户列表（仅管理员）"""
    page = request.args.get('page', 1, type=int)
    per_page = request.args.get('per_page', 20, type=int)
    role = request.args.get('role')
    is_active = request.args.get('is_active')
    
    # 构建查询
    query = User.query
    
    if role:
        query = query.filter_by(role=role)
    
    if is_active is not None:
        is_active = is_active.lower() == 'true'
        query = query.filter_by(is_active=is_active)
    
    # 分页
    pagination = query.paginate(page=page, per_page=per_page)
    
    return jsonify({
        "total": pagination.total,
        "pages": pagination.pages,
        "page": page,
        "per_page": per_page,
        "users": [user.to_dict() for user in pagination.items]
    }), 200

@api_v1.route('/users/<int:user_id>', methods=['GET'])
@jwt_required()
def get_user(user_id):
    """获取用户详情"""
    # 普通用户只能查看自己，管理员可以查看所有人
    if not current_user.is_admin and current_user.id != user_id:
        raise ForbiddenError("权限不足")
    
    user = User.query.get_or_404(user_id)
    
    return jsonify(user.to_dict()), 200

@api_v1.route('/users', methods=['POST'])
@admin_required
def create_user():
    """创建用户（仅管理员）"""
    data = request.get_json()
    
    schema = UserSchema()
    try:
        # 使用schema验证数据
        schema.load(data)
    except Exception as e:
        return jsonify({"msg": str(e), "errors": e.messages if hasattr(e, 'messages') else None}), 400
    
    # 创建新用户
    user = User(
        username=data['username'],
        email=data['email'],
        full_name=data.get('full_name'),
        role=data.get('role', UserRole.USER.value),
        is_active=data.get('is_active', True)
    )
    user.set_password(data['password'])
    
    db.session.add(user)
    db.session.commit()
    
    return jsonify({
        "msg": "用户创建成功",
        "user": user.to_dict()
    }), 201

@api_v1.route('/users/<int:user_id>', methods=['PUT'])
@jwt_required()
def update_user(user_id):
    """更新用户信息"""
    # 普通用户只能更新自己，管理员可以更新所有人
    if not current_user.is_admin and current_user.id != user_id:
        raise ForbiddenError("权限不足")
    
    user = User.query.get_or_404(user_id)
    data = request.get_json()
    
    schema = UserUpdateSchema(context={'user_id': user_id})
    try:
        # 使用schema验证数据
        schema.load(data)
    except Exception as e:
        return jsonify({"msg": str(e), "errors": e.messages if hasattr(e, 'messages') else None}), 400
    
    # 只有管理员可以更新角色和激活状态
    if current_user.is_admin:
        if 'role' in data:
            user.role = data['role']
        if 'is_active' in data:
            user.is_active = data['is_active']
    
    # 所有用户都可以更新的字段
    if 'full_name' in data:
        user.full_name = data['full_name']
    if 'email' in data:
        user.email = data['email']
    
    db.session.commit()
    
    return jsonify({
        "msg": "用户更新成功",
        "user": user.to_dict()
    }), 200

@api_v1.route('/users/<int:user_id>', methods=['DELETE'])
@admin_required
def delete_user(user_id):
    """删除用户（仅管理员）"""
    user = User.query.get_or_404(user_id)
    
    # 防止删除自己
    if user.id == current_user.id:
        return jsonify({"msg": "不能删除当前登录的用户"}), 400
    
    db.session.delete(user)
    db.session.commit()
    
    return jsonify({
        "msg": "用户删除成功"
    }), 200 